package com.qyer.search.model.aggregation;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.collections4.CollectionUtils;

import java.util.*;
/**
 * Created by tangzheng on 16/7/17.
 */
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Country implements Comparable<Country>{

  @JsonProperty
  private int id;
  @JsonProperty
  private String name;
  @JsonProperty
  private int cid;
  //@JsonInclude(JsonInclude.Include.NON_NULL)
  @JsonProperty
  private List<City> city;
  @JsonProperty
  private int size;

  public Country(int id, String name, int cid, List<City> city) {
    this.id = id;
    this.name = name;
    this.cid = cid;
    this.city = city;
  }

  public Country(int id, String name, int cid, List<City> city, int size) {
    this.id = id;
    this.name = name;
    this.cid = cid;
    this.city = city;
    this.size = size;
  }

  public Country(int id, String name, int cid, int size) {
    this.id = id;
    this.name = name;
    this.cid = cid;
    this.size = size;
  }

  public int getSize() {
    return size;
  }

  public void setSize(int size) {
    this.size = size;
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getCid() {
    return cid;
  }

  public void setCid(int cid) {
    this.cid = cid;
  }

  public List<City> getCity() {
    return city;
  }

  public void setCity(List<City> city) {
    this.city = city;
  }

  @Override public boolean equals(Object o) {
    if (this == o)
      return true;
    if (o == null || getClass() != o.getClass())
      return false;

    Country country = (Country) o;

    return id == country.id;

  }

  @Override public int hashCode() {
    return id;
  }

  @Override public int compareTo(Country country) {
    return (country.getSize() - this.size);
  }

  public void add(Country country){
    if(this.name.equals(country.getName())){
      this.size += country.getSize();
      if(country.getCity() != null){
        for(City city2:country.getCity()){
          this.add(city2);
        }
      }
    }
  }

  public void add(City cityt){
    boolean isFound = false;
    for(City city1:city){
      if(city1.equals(cityt)){
        city1.add(cityt);
        isFound = true;
        break;
      }
    }
    if(!isFound){
      city.add(cityt);
    }
  }

  public void sort(){
    if(CollectionUtils.isNotEmpty(city)){
      Collections.sort(city);
    }
  }
}
